<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { TypePageDTO } from '@src/interfaces/TypePageDTO.ts'
import { deleteAdminsApi, getAdminListApi } from '@src/apis/adminApi.ts'
import { TypeAdmin } from '@src/interfaces/TypeAdmin.ts'
import { ElMessage } from 'element-plus'
import Pagination from '@src/components/Pagination.vue'

const page = ref<TypePageDTO<TypeAdmin>>({
  current: 1,
  size: 10,
  total: 0,
  records: [],
})
const search = ref({
  name: '',
  phone: '',
  account: '',
})

const getAdminList = () => {
  getAdminListApi({
    page: page.value.current,
    size: page.value.size,
    ...search.value,
  }).then((res) => {
    page.value = res.data
  })
}

const handleCurrentChange = (value: number) => {
  page.value.current = value
  getAdminList()
}
const handleSizeChange = (value: number) => {
  page.value.size = value
  getAdminList()
}

onMounted(() => {
  getAdminList()
})

watch(search, getAdminList, { deep: true })

const selectIds = ref<number[]>([])
const handleSelect = (admins: TypeAdmin[]) => {
  selectIds.value = []
  admins.forEach((admin) => {
    selectIds.value.push(<number>admin.id)
  })
}

/**
 * 批量删除管理员
 */
const deleteAdmins = () => {
  deleteAdminsApi(selectIds.value).then(() => {
    ElMessage.success('删除成功')
    getAdminList()
  })
}
</script>

<template>
  <div>
    <h2><el-text>后台管理员</el-text></h2>
    <div class="input-box">
      <el-input v-model="search.name" placeholder="输入名称"></el-input>
      <el-input v-model="search.phone" placeholder="输入手机号"></el-input>
      <el-input v-model.trim="search.account" placeholder="输入账号"></el-input>
      <el-button type="primary">搜索</el-button>
      <el-popconfirm
        @confirm="deleteAdmins"
        :title="`确定删除${selectIds.length}项吗？`"
      >
        <template #reference>
          <el-button type="danger" :disabled="selectIds.length === 0"
            >批量删除</el-button
          >
        </template>
      </el-popconfirm>
    </div>
    <div class="table-box">
      <el-table
        :data="page?.records"
        @selection-change="handleSelect"
        height="720"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="id" label="管理员ID"></el-table-column>
        <el-table-column prop="name" label="名称"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column prop="account" label="账号"></el-table-column>
      </el-table>
    </div>
    <div class="page">
      <Pagination
        :page="page.current"
        :size="page.size"
        :total="page.total"
        @page-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<style scoped lang="less">
h2 {
  text-align: center;
  .el-text {
    font-size: 2em;
  }
}

.input-box {
  display: flex;

  & > * {
    margin: 0 10px;
  }
}
</style>
